//package org.example.gradlemultipledatasourcedemo.config.config2;
//
//import com.zaxxer.hikari.HikariDataSource;
//import org.example.gradlemultipledatasourcedemo.config.DataSourceConfigProperties;
//import org.example.gradlemultipledatasourcedemo.config.MultiDataSourceProperties;
//import org.mybatis.spring.SqlSessionFactoryBean;
//import org.mybatis.spring.mapper.MapperScannerConfigurer;
//import org.springframework.beans.BeansException;
//import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
//import org.springframework.beans.factory.config.RuntimeBeanReference;
//import org.springframework.beans.factory.support.BeanDefinitionRegistry;
//import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
//import org.springframework.beans.factory.support.GenericBeanDefinition;
//import org.springframework.boot.context.properties.bind.Binder;
//import org.springframework.context.EnvironmentAware;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.env.Environment;
//
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//@Configuration
//public class DynamicDataSourceRegistrar implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
//
//    private Environment environment;
//
//    @Override
//    public void setEnvironment(Environment environment) {
//        this.environment = environment;
//    }
//
//    @Override
//    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
//
//        //        // 先删除 Spring Boot 自动注册的默认 DataSource（避免冲突）
//        if (registry.containsBeanDefinition("dataSource")) {
//            registry.removeBeanDefinition("dataSource");
//            System.out.println("⚙️ 已移除 Spring Boot 默认数据源 BeanDefinition");
//        }
//        MultiDataSourceProperties configs = Binder.get(environment)
//                .bind("spring.datasource", MultiDataSourceProperties.class)
//                .orElse(null);
//
//        if (configs == null || configs.getConfigs() == null || configs.getConfigs().isEmpty()) {
//            throw new IllegalStateException("No datasource configurations found");
//        }
//
//        List<DataSourceConfigProperties> list = configs.getConfigs();
//
//        Map<Object, Object> targetDataSources = new HashMap<>();
//
//        for (int i = 0; i < list.size(); i++) {
//            DataSourceConfigProperties conf = list.get(i);
//
//            // 1️⃣ 注册 HikariDataSource
//            GenericBeanDefinition dsDef = new GenericBeanDefinition();
//            dsDef.setBeanClass(HikariDataSource.class);
//            dsDef.getPropertyValues().add("jdbcUrl", conf.getUrl());
//            dsDef.getPropertyValues().add("username", conf.getUsername());
//            dsDef.getPropertyValues().add("password", conf.getPassword());
//            dsDef.getPropertyValues().add("driverClassName", conf.getDriverClassName());
//            String dsBeanName = conf.getName() + "DataSource";
//            registry.registerBeanDefinition(dsBeanName, dsDef);
//
//            targetDataSources.put(conf.getName(), dsDef.getBeanClassName() != null ? dsDef.getBeanClass() : dsBeanName);
//
//            // 2️⃣ 注册 SqlSessionFactory
//            GenericBeanDefinition factoryDef = new GenericBeanDefinition();
//            factoryDef.setBeanClass(SqlSessionFactoryBean.class);
//            factoryDef.getPropertyValues().add("dataSource", new RuntimeBeanReference(dsBeanName));
//            String factoryBeanName = conf.getName() + "SqlSessionFactory";
//            registry.registerBeanDefinition(factoryBeanName, factoryDef);
//
//            // 3️⃣ 注册 MapperScannerConfigurer
//            GenericBeanDefinition scannerDef = new GenericBeanDefinition();
//            scannerDef.setBeanClass(MapperScannerConfigurer.class);
//            scannerDef.getPropertyValues().add("basePackage", conf.getBasePackage());
//            scannerDef.getPropertyValues().add("sqlSessionFactoryBeanName", factoryBeanName);
//            scannerDef.setDependsOn(factoryBeanName);
//            registry.registerBeanDefinition(conf.getName() + "MapperScannerConfigurer", scannerDef);
//
//            System.out.printf("✅ 数据源 [%s] 注册完成，扫描包：%s%n", conf.getName(), conf.getBasePackage());
//        }
//
//        // 4️⃣ 注册 DynamicRoutingDataSource
//        GenericBeanDefinition routingDef = new GenericBeanDefinition();
//        routingDef.setBeanClass(DynamicRoutingDataSource.class);
//        routingDef.getPropertyValues().add("targetDataSources", targetDataSources);
//        routingDef.getPropertyValues().add("defaultTargetDataSource", new RuntimeBeanReference(list.get(0).getName() + "DataSource"));
//        registry.registerBeanDefinition("dataSource", routingDef);
//    }
//
//    @Override
//    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
//        // 无需处理
//    }
//}
